package cn.com.kisen.db.mongo;

import java.util.Date;
import java.util.HashSet;
import java.util.Stack;

import org.apache.log4j.Logger;

import com.mongodb.MongoClient;

/**
 * @author   Administrator
 * @creation 2017年9月8日 下午4:15:27
 *
 */
public class MongoClientPool {

    private Logger logger = Logger.getLogger(MongoClientPool.class);

    // occupied mongo clients
    private HashSet<MongoClient> occupied = new HashSet<MongoClient>();

    // idle mongo clients
    private Stack<MongoClient> idle = new Stack<MongoClient>();

    private MongoClientPool(){
        String server = "localhost";
        int port = 27017;
        int initAmount = 10;

        // initial mongo clients
        long start = new Date().getTime();
        for(int i = 0; i < initAmount; i++){
            this.idle.push(new MongoClient(server,port));
        }
        long end = new Date().getTime();
        logger.debug("initialize clients with " + new Long(end -start).toString() + "ms");
    }

    private static MongoClientPool instance =  new MongoClientPool();


    public static MongoClientPool getInstance(){
        return instance;
    }

    /**
     * 获取客户端
     * @return
     */
    public synchronized MongoClient getMongoClient(){
        long start = new Date().getTime();
        if(idle.isEmpty()){
            return null;
        }
        MongoClient client = idle.pop();
        occupied.add(client);
        long end = new Date().getTime();
        logger.debug("get a client with " + new Long(end -start).toString() + "ms");
        return client;
    }

    /**
     * 放弃客户端
     * @param client
     */
    public synchronized void dropMongoClient(MongoClient client){
        long start = new Date().getTime();
        occupied.remove(client);
        idle.push(client);
        long end = new Date().getTime();
        logger.debug("release a client with " + new Long(end -start).toString() + "ms");
    }
}
